﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace DMSMT.Tool
{
    public partial class HttpReqFrm : Form
    {
        //string uri = null;
        //CookieContainer cookieContainer = null;
        List<Cookie> pCookie = null;

        public HttpReqFrm()
        {
            InitializeComponent();
        }

        private string HttpPost(string Url, string postDataStr)
        {
            //byte[] bs = Encoding.ASCII.GetBytes(param);
            //req.ContentLength = bs.Length;
            /*using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }*/

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            //request.AllowAutoRedirect = false;
            
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            CookieContainer cookie = new CookieContainer();
            request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            string retString = "";
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {

                //response.Cookies = cookie.GetCookies(response.ResponseUri);

                //CookieCollection rescookies = response.Cookies;
                //Log.LogText("rescookies.Count:\t" + rescookies.Count.ToString());
                //if (rescookies.Count > 0)
                //{
                //    //HttpCookie[] dest = new HttpCookie[cookies.Count];
                //    //cookies.CopyTo(dest, 0);
                //    //for (int i = 0; i < dest.Length; i++)
                //    //{
                //    //    cookieCollection.AddCookie(dest[i], true);
                //    //}
                //    for (int i = 0; i < rescookies.Count; i++)
                //    {
                //        Log.LogText(rescookies[i].Name + rescookies[i].Value);
                //    }

                //}

                //Uri uri=response.ResponseUri;
                //cookieContainer = new CookieContainer();
                pCookie = new List<Cookie>();
                CookieCollection reqcookies = cookie.GetCookies(response.ResponseUri);
                if (reqcookies.Count > 0)
                {
                    for (int i = 0; i < reqcookies.Count; i++)
                    {
                        pCookie.Add(new Cookie(reqcookies[i].Name, reqcookies[i].Value));
                    }
                }

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }

            return retString;
        }

        /*
         Encoding myEncoding = Encoding.GetEncoding("gb2312");
             string address = "http://www.jb51.net/?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
             HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
             req.Method = "GET";
             using (WebResponse wr = req.GetResponse())
             {
             //在这里对接收到的页面内容进行处理
             }
         */
        public string HttpGet(string url, string postDataStr)
        {
            string requrl = url;
            if (string.IsNullOrEmpty(postDataStr))
                requrl += "?" + postDataStr;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requrl);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            //request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)";
            request.Accept = "*/*";
            //如果方法验证网页来源就加上这一句如果不验证那就可以不写了
            //request.Referer = uri;
            CookieContainer cookies = new CookieContainer();

            for (int i = 0; i < pCookie.Count; i++)
            {
                cookies.Add(new Uri(url),pCookie[i]);
            }
            request.CookieContainer = cookies;

            string retString = "";
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            return retString;
        }

        public string HttpGet(string url)
        {
            return HttpGet(url,null);
        }

        private void btSendReq_Click(object sender, EventArgs e)
        {
            string url = tbUrl.Text.Trim();
            string param = rtbData.Text.Trim();
            if (url == "")
            {
                MessageBox.Show("请求地址不能为空");
                return;
            }
            string retString = HttpPost(url, param);

            JObject o = JObject.Parse(retString);
            //Console.WriteLine(o["Tbody"].ToString());
            //Log.LogText(o["msg"].ToString());
            string msg = o["msg"].ToString();
          if (string.IsNullOrEmpty(msg))
            {
                Log.LogText("连接服务器失败");
            }
            else
            {
                if (msg.Equals("success"))
                {
                    Log.LogText("success");
                    url = "http://localhost:1400/DMS/system/menuAction!toMenuAction.action";
                    retString = HttpGet(url);
                    //Log.LogText(retString);
                    int index=retString.IndexOf("版本号:");
                    int indexE = retString.IndexOf("'", index);
                    string ver=retString.Substring(index, indexE - index);
                    Log.LogText(ver);
                }
                else
                {
                    Log.LogText(retString);
                }
            }

            //JArray json = (JArray)o["Tbody"];
            //for (int j = 0; j < json.Count; j++)
            //{
            //    JObject jsonobj = (JObject)json[j];
            //    Console.WriteLine(jsonobj["BBS_Title"].ToString() + "|" + jsonobj["Hits"].ToString());
            //}
        }
    }
}
